import React,{useEffect,useState}from 'react'
import { PageHeader, Button ,Modal,Form,Input, message} from 'antd';
import moment  from 'moment';
import E from 'wangeditor'
import {ArticleAddApi,ArticleSearchApi,ArticleUpdateApi} from '../request/api'

import {useParams,useNavigate,useLocation} from 'react-router-dom'
let editor = null



// 组件
export default function Edit() {
  const [form] = Form.useForm();
  const [content,setContent] = useState()
  const [title,setTitle] = useState()
  const [subTitle,setSubTitle] = useState()
  const [isModalVisible, setIsModalVisible] = useState(false);
  const params = useParams()
  const navigate = useNavigate()
  const location = useLocation()


  const delData =(errCode,msg)=>{
      // 判断是否修改成功
      if(errCode === 0){
        // console.log(res);
        message.success(msg)
        // 跳回列表页
        navigate('/listlist')
      }else{
        message.error(msg)
      }
      // 关闭对话框
      setIsModalVisible(false)
  }
  

  // 对话框点击提交事件
  const handleOk = () => {
    form
          .validateFields()
          .then(values => {
            form.resetFields();
            let {title,subTitle} = values;

            // 地址栏是否有id，有id代表进入的是编辑，发送编辑的请求，没有id代表进入的是添加文章
            if(params.id){
              // 更新文章的请求
              ArticleUpdateApi({title,subTitle,content,id:params.id}).then(res=>delData(res.errCode,res.message))
            }else{
               // 发送请求添加文章
            ArticleAddApi({title,subTitle,content}).then(res=>es=>delData(res.errCode,res.message))
          }
           
          })
          .catch(()=>{
            return;
          });
  };

  // 模拟componentDidMount生命周期

  useEffect(()=>{
    editor = new E('#div1')

    editor.config.onchange = (newHtml)=>{
      setContent(newHtml)
    }
    editor.create()
    // 根据地址id做请求
    if(params.id){
      ArticleSearchApi({id:params.id}).then(res=>{
        console.log(res);
        if(res.errCode === 0){
          editor.txt.html(res.data.content) //重新设置编辑器的内容
          setTitle(res.data.title)
          setSubTitle(res.data.subTitle)
        }
      })
    }

    return ()=>{
      // 模拟组件销毁
      editor.destroy()
    }
  },[location.pathname])
  return (
    <div>
    <PageHeader
      ghost={false}
      onBack={params.id ? () => window.history.back():null}
      title="文章编辑"
      subTitle={"当前日期:"+moment(new Date()).format('YYYY-MM-DD')}
      extra={<Button key="1" type="primary" onClick={() => {setIsModalVisible(true);}}>提交文章</Button>}
    ></PageHeader>
    <div style={{padding:'0 20px 20px',background:'#fff'}} id="div1">
    <Modal zIndex={99999} title="填写文章标题" okText='提交' cancelText='取消'  visible={isModalVisible} onOk={handleOk} onCancel={() => {setIsModalVisible(false);}}>
       {/* 表单 */}
       <Form
      form={form}
      name="basic"
      labelCol={{span: 4}}
      wrapperCol={{span: 20,}}
      autoComplete="off"
      initialValues={{title:title,subTitle:subTitle}}
    >
      <Form.Item
        label="标题"
        name="title"
        rules={[
          {
            required: true,
            message: '请填写标题',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item label="副标题"name="subTitle">
        <Input />
      </Form.Item>
    </Form>
      </Modal>

    </div>
    </div>
  )
}
